<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    :action="uploadApi"
    :limit="1"
    name="uploadFile"
    accept=".xlsx,.xls"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :auto-upload="false"
  >
    <template #trigger>
      <el-button type="primary">选择文件</el-button>
    </template>
    <el-button style="margin-left: 10px" class="ml-3" type="success" @click="submitUpload"
      >上传文件</el-button
    >
    <template #tip>
      <div class="el-upload__tip text-red">只能上传xls/xlsx，且不超过一个</div>
    </template>
  </el-upload>
</template>

<script setup>
import { ref } from 'vue'
import { genFileId, ElNotification } from 'element-plus'
const uploadApi = ref('/api/file/update')
const upload = ref()

// 文件类型验证
const beforeUpload = (rawFile) => {
  const fileType = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const fileTypeList = ['xls', 'xlsx']
  if (!fileTypeList.includes(fileType)) {
    ElNotification({
      title: 'Error',
      message: '请上传xls/xlsx和pptx文件',
      type: 'error',
      duration: 2000
    })
    return false
  }
  return true
}
// 当超出限制时，执行的钩子函数
const handleExceed = (files) => {
  upload.value?.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}
// 提交文件
const submitUpload = () => {
  upload.value.submit()
}
</script>

<style lang="scss" scoped></style>
